#include "Tree.h"
#include "Queue.h"

#define _CRT_SECURE_NO_WARNINGS 1


void BinaryTreePrevOrder(BTNode* root)
{
	if (root == NULL)
	{
		printf("NULL ");
		return;
	}
	printf("%c ", root->data);
	BinaryTreePrevOrder(root->left);
	BinaryTreePrevOrder(root->right);
}

void BinaryTreeInOrder(BTNode* root)
{
	if (root == NULL)
	{
		printf("NULL ");
		return;
	}
	BinaryTreeInOrder(root->left);
	printf("%c ", root->data);
	BinaryTreeInOrder(root->right);
}

void BinaryTreePostOrder(BTNode* root)
{
	if (root == NULL)
	{
		printf("NULL ");
		return;
	}
	BinaryTreePostOrder(root->left);
	BinaryTreePostOrder(root->right);
	printf("%c ", root->data);
}


int BinaryTreeSize(BTNode* root)
{
	if (root == NULL)
	{
		return 0;
	}
	return 1 + BinaryTreeSize(root->left) + BinaryTreeSize(root->right);
}

int BinaryTreeLeafSize(BTNode* root)
{
	if (root == NULL)
	{
		return 0;
	}
	if (root->left == NULL && root->right == NULL)
	{
		return 1;
	}
	return BinaryTreeLeafSize(root->left) + BinaryTreeLeafSize(root->right);
}

int BinaryTreeLevelKSize(BTNode* root, int k)
{
	if (root == NULL)
	{
		return 0;
	}
	if (k == 1)
	{
		return 1;
	}
	return BinaryTreeLevelKSize(root->left, k - 1) + BinaryTreeLevelKSize(root->right, k - 1);
}

BTNode* BinaryTreeFind(BTNode* root, BTDataType x)
{
	if (root == NULL)
	{
		return NULL;
	}
	if (x == root->data)
	{
		return root;
	}
	BTNode* leftFind = BinaryTreeFind(root->left, x);
	if (leftFind)
	{
		return leftFind;
	}
	BTNode* rightFind = BinaryTreeFind(root->right, x);
	if (rightFind)
	{
		return rightFind;
	}
	return NULL;
}

int BinaryTreeDepth(BTNode* root)
{
	if (root == NULL)
	{
		return 0;
	}
	int leftTreeDep = BinaryTreeDepth(root->left);
	int rightTreeDep = BinaryTreeDepth(root->right);
	return 1 + (leftTreeDep > rightTreeDep ? leftTreeDep : rightTreeDep);
}

void BinaryTreeDestory(BTNode** root)
{
	if (*root == NULL)
	{
		return;
	}
	BinaryTreeDestory(&(*root)->left);
	BinaryTreeDestory(&(*root)->right);
	free(*root);
	*root = NULL;
}

void LevelOrder(BTNode* root)
{
	Queue q;
	QInit(&q);
	QPush(&q, root);
	while (!Empty(&q))
	{
		BTNode* top = QFront(&q);
		QPop(&q);
		printf("%c ", top->data);
		if(top->left)
		    QPush(&q, top->left);
		if(top->right)
			QPush(&q, top->right);
	}
	printf("\n");
	QDesTory(&q);
}

bool BinaryTreeComplete(BTNode* root)
{
	Queue q;
	QInit(&q);
	QPush(&q, root);
	while (!Empty(&q))
	{
		BTNode* top = QFront(&q);
		QPop(&q);
		if (top == NULL)
		{
			break;
		}
		QPush(&q, top->left);
		QPush(&q, top->right);
	}
	while (!Empty(&q))
	{
		BTNode* top = QFront(&q);
		QPop(&q);
		if (top)
		{
			QDesTory(&q);
			return false;
		}
	}
	QDesTory(&q);
	return true;
}




